package com.yuanyefu.jdbc;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2017/9/19 0019.
 */
public class RegisterServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html;charset=GBK";

    public void init()  throws ServletException {

    }
    public void destroy(){
        super.destroy();
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType(CONTENT_TYPE);
        request.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String sex = request.getParameter("sex");
        int age = Integer.parseInt(request.getParameter("age"));
        TRegister rg = new TRegister();
        rg.setAge(age);
        rg.setSex(sex);
        rg.setUserName(userName);
        rg.setUserPwd(userPwd);
        Session session = HibernateUtil.currentSession();//生成Session实例
        Transaction tx = session.beginTransaction();
        try {
            session.save(rg);    //保存持久类对象
            tx.commit();        //提交到数据库
            session.close();
            response.sendRedirect("registerOK.jsp");
        }catch (HibernateException exception){
            exception.printStackTrace();
            tx.rollback();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}
